package region

import (
	"context"

	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendDeleteRegionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendDeleteRegionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendDeleteRegionLogic {
	return &BackendDeleteRegionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// group: region
func (l *BackendDeleteRegionLogic) BackendDeleteRegion(in *setting.IDReq) (*setting.BaseResp, error) {
	id := in.Id
	if id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	filterMap := make(map[string]map[string][]any)
	filterMap[model.SysRegionColumns.ParentID] = map[string][]any{
		"equalTo": []any{id},
	}
	filterMap[model.SysRegionColumns.Status] = map[string][]any{
		"notEqualTo": []any{globalkey.StatusDeleted},
	}
	_, count, err := l.svcCtx.SysRegion.GetList(l.ctx, model.M{}, 0, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if count > 0 {
		logx.Errorw("delete region failed, please check its children had been deleted",
			logx.Field("regionId", id))
		return nil, errorx.NewInvalidArgumentError("region.deleteChildrenDesc")
	}

	err = l.svcCtx.SysRegion.SoftDelete(l.ctx, nil, id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &setting.BaseResp{
		Msg: i18n.DeleteSuccess,
	}, nil
}
